<?php
// +----------------------------------------------------------------------
// | MubinAdmin
// +----------------------------------------------------------------------
// | 版权所有 2015~2020 泉州市牧滨电子商务有限公司 [ http://www.mubin.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.mubin.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/mubin/MubinAdmin
// +----------------------------------------------------------------------

namespace app\admin\logic;

use app\admin\model\AdminUser;
use app\common\traits\BaseLogic;
use think\facade\{Request,Config};

class AdminUserLogic
{
	use BaseLogic;

	private $model;

	public function __construct()
	{
		$this->model = new AdminUser();
	}

    /**
     * 管理员登录
     * @param string|null $username
     * @param string|null $password
     * @param int|null    $type
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userLogin(?string $username = null, ? string $password = null, ?int $type = null)
    {
        switch ($type) {
            case 1:
                $field = 'username';
                break;
            case 2:
                $field = 'email';
                break;
            case 3:
                $field = 'mobile';
                break;
            case 4:
                $field = 'id';
                break;
            default:
                $this->error='用户名不正确 -103';
                return false;
        }
        //获取用户数据
        $object=$this->model->where($field,'=', $username)->field(['id', 'status', 'password'])->find();
        if (!$object || (int)$object->status !== 1) {
            $this->error='用户不存在或被禁用';
            return false;
        }
        //验证用户密码
        if (ucenter_md5($password) !== $object->password) {
            $this->error='用户名或者密码错误';
            return false;
        }
        //更新用户登录信息
        $object->last_login_time=Request::time();
        $object->last_login_ip=ip2long(Request::ip());
        $object->save();
        return (int)$object->id;
    }

    /**
     * 管理员登录信息
     * @param int|null $userId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userInfo(?int $userId)
    {
        $object = $this->model->where('id','=', $userId)->find();
        if (!$object || (int)$object->status !== 1) {
            $this->error = '用户不存在或已被禁用！';
            return false;
        }
        return $object;
    }
}